import { Form, Input, Modal, Select, App } from 'antd';
import type { Product } from './types';

interface AddListProps{
    isModalOpen:boolean,
    handlClose: ()=> void,
    onAdd: (newProduct: Product) => void
}

const AddList = ({isModalOpen , handlClose, onAdd}:AddListProps) => {
  const [form] = Form.useForm()
  const { message } = App.useApp()
  
  const handleOk = async () => {
    try {
      const values = await form.validateFields()
      // 生成新的ID（简单递增）
      const newProduct = {
        id: Date.now(), // 用时间戳作为ID
        name: values.name,
        price: Number(values.price),
        description: values.description,
        createTime: new Date().toISOString().split('T')[0],
        updateTime: new Date().toISOString().split('T')[0],
        status: values.status === 'success' ? 'Success' : values.status === 'failed' ? 'Error' : values.status === 'pending' ? 'Pending' : 'Pending'
      }
      onAdd(newProduct)
      form.resetFields()
      handlClose()
      message.success('产品添加成功！')
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  };

  const handleCancel = () => {
    form.resetFields()
    handlClose()
  };

  return (
    <>
      <Modal
        title="添加新产品"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
       <Form layout='vertical' form={form}>
          <Form.Item label="产品名称" name="name" rules={[{required: true, message: '请输入产品名称'}]}>
            <Input />
          </Form.Item>
          <Form.Item label="产品价格" name="price" rules={[{required: true, message: '请输入产品价格'}]}>
            <Input type="number" />
          </Form.Item>
          <Form.Item label="产品描述" name="description" rules={[{required: true, message: '请输入产品描述'}]}>
            <Input />
          </Form.Item>
          <Form.Item label="产品状态" name="status" rules={[{required: true, message: '请选择产品状态'}]} initialValue='success'>
            <Select options={[{label: '成功', value: 'success'}, {label: '失败', value: 'failed'}, {label: '等待', value: 'pending'}]} />  
          </Form.Item>
       </Form>
      </Modal>
    </>
  );
};

export default AddList;